<!DOCTYPE html>

<html lang="en">


<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>照片加水印示例</title>
</head>

<body>
    <canvas style="display: none"></canvas>
    <img style="display: none" src="" alt="Example Image" @load="addWatermark" />
    <input type="file" id="file" multiple="multiple">
    <script>
        const filesDOM = document.querySelector('#file')
        const canvas = document.getElementsByTagName('canvas')[0]
        let current = 0
        const img = document.getElementsByTagName('img')[0];
        const array_url = []
        filesDOM.addEventListener('change', () => {
            const array = [...filesDOM.files]
            array.forEach(item => array_url.push(window.URL.createObjectURL(item)))
            img.src = array_url[current]
        })
        wmConfig = {
            font: "microsoft yahei", //字体
            textArray: ['张三', '2021/11/26 16:44'],//水印文本内容，允许数组最大长度3 即：3行水印
            density: 5  //密度 建议取值范围1-5   值越大，水印越多，可能会导致水印重叠等问题，慎重！！！
        }

        //开始绘画水印
        const drawWaterMark = (ctx, imgWidth, imgHeight, wmConfig) => {
            let fontSize;
            if (imgWidth >= 3456) {
                fontSize = 50;
            } else if (imgWidth >= 2700) {
                fontSize = 30;
            } else if (imgWidth >= 2000) {
                fontSize = 26;
            } else if (imgWidth >= 1436) {
                fontSize = 20;
            } else if (imgWidth >= 800) {
                fontSize = 12;
            } else if (imgWidth >= 500) {
                fontSize = 10;
            } else {
                fontSize = 8;
            }
            console.log(imgWidth, imgHeight, fontSize);
            ctx.fillStyle = "black";

            ctx.font = `${fontSize}px ${wmConfig.font}`;
            ctx.lineWidth = 1;
            ctx.fillStyle = "rgba(255,255,255,0.3)";
            ctx.textAlign = "left";
            ctx.textBaseline = "middle";


            //文字坐标

            const maxPx = Math.max(imgWidth, imgHeight);

            const stepPx = Math.floor(maxPx / wmConfig.density);


            let arrayX = [0];//初始水印位置 canvas坐标 0 0 点
            while (arrayX[arrayX.length - 1] < maxPx / 2) {
                arrayX.push(arrayX[arrayX.length - 1] + stepPx);

            }
            arrayX.push(...arrayX.slice(1, arrayX.length).map((el) => {
                return -el;
            }));


            for (let i = 0; i < arrayX.length; i++) {
                for (let j = 0; j < arrayX.length; j++) {
                    ctx.save();
                    ctx.translate(imgWidth / 2, imgHeight / 2); ///画布旋转原点 移到 图片中心
                    ctx.rotate(-Math.PI / 5);
                    if (wmConfig.textArray.length > 3) {
                        wmConfig.textArray = wmConfig.textArray.slice(0, 3);
                    }
                    wmConfig.textArray.forEach((el, index) => {
                        let offsetY = fontSize * index + 2;
                        ctx.fillText(el, arrayX[i], arrayX[j] + offsetY);
                    });
                    ctx.restore();
                }
            }
            downloadFile(canvas.toDataURL("image/png"), new Date().valueOf())
        };
        //添加文字水印
        const addTextWatermark = (ctx, canvas) => {
            // 设置文字水印样式
            ctx.font = "30px Arial";
            ctx.fillStyle = "rgba(255, 255, 255, 0.5)";
            ctx.textAlign = "center";
            ctx.textBaseline = "middle";
            ctx.rotate(-0.1);  // 旋转角度
            drawWaterMark(ctx, canvas.width, canvas.height, wmConfig)
        }
        //添加图片水印
        const addImageWatermark = (ctx, canvas) => {
            const watermarkImage = new Image();
            watermarkImage.src = 'path/to/watermark.png';  // 替换为你的水印图片路径
            watermarkImage.onload = () => {
                const scaleFactor = 0.3;  // 调整水印图片大小
                const watermarkWidth = watermarkImage.width * scaleFactor;
                const watermarkHeight = watermarkImage.height * scaleFactor;
                // 绘制图片水印
                ctx.drawImage(watermarkImage, canvas.width - watermarkWidth - 10, canvas.height - watermarkHeight - 10, watermarkWidth, watermarkHeight);
            };
        }
        // 监听图片加载事件
        document.getElementsByTagName('img')[0].addEventListener('load', function (event) {
            const canvas = document.getElementsByTagName('canvas')[0];
            const img = document.getElementsByTagName('img')[0];
            const ctx = canvas.getContext('2d');

            // 设置 canvas 大小与图片相同
            canvas.width = img.width;
            canvas.height = img.height;

            // 绘制图片
            ctx.drawImage(img, 0, 0);

            // 根据需要添加图片或文字水印
            addTextWatermark(ctx, canvas);  // 添加文字水印
        });

        // base64下载为图片
        function downloadFile(content, fileName) { //下载base64图片
            const base64ToBlob = function (code) {
                let parts = code.split(';base64,');
                let contentType = parts[0].split(':')[1];
                let raw = window.atob(parts[1]);
                let rawLength = raw.length;
                let uInt8Array = new Uint8Array(rawLength);
                for (let i = 0; i < rawLength; ++i) {
                    uInt8Array[i] = raw.charCodeAt(i);
                }
                return new Blob([uInt8Array], {
                    type: contentType
                });
            };
            let aLink = document.createElement('a');
            let blob = base64ToBlob(content); //new Blob([content]);
            let evt = document.createEvent("HTMLEvents");
            evt.initEvent("click", true, true); //initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
            aLink.download = fileName;
            aLink.href = URL.createObjectURL(blob);
            // aLink.click();
            aLink.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, view: window }));  //
            // 下载完之后开始下一张图片
            if (current < array_url.length) {
                current += 1
                img.src = array_url[current]
            } else {
                // 释放资源
                array_url.forEach(item => URL.revokeObjectURL(item))

            }
        }
    </script>


</body>


</html>